package com.innazis.jfrogsurvey.backendmanager;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

import com.innazis.jfrogsurvey.config.Constants;
import com.innazis.jfrogsurvey.obj.ServerResponse;
import com.innazis.jfrogsurvey.obj.SurveyObj;

/**
 * Created by Inna on 04.06.14.
 */
public final class BackendManager {

    private static final String DISPLAY_MESSAGE_ACTION = "BackendManager";
    private static final int MAX_ATTEMPTS = 3;
    private static final int BACKOFF_MILLI_SECONDS = 2000;
    private static final Random random = new Random();

    public int sendData(List<SurveyObj> AllSurveys, String senderID) {
        long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000);
        int error = Constants.FAILED;

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpConnectionParams
                .setConnectionTimeout(httpClient.getParams(), 10000); // Timeout
        // Limit
        HttpResponse response;
        JSONObject json = ParameterUtility.CreateSendDataParamsJSON(AllSurveys, senderID);
        for (int i = 1; i <= MAX_ATTEMPTS; i++) {
        try {
            HttpPost post = new HttpPost(Constants.URL_SEND_DATA);
            StringEntity se = new StringEntity(json.toString(), HTTP.UTF_8);
            se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));
            post.setHeader("Content-type", "application/json;charset=UTF-8");
            post.setEntity(se);

            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String responseBody = httpClient.execute(post, responseHandler);
            JSONObject responseObj = new JSONObject(responseBody);
            ServerResponse resp = new ServerResponse();
            /* Checking response */
            if (responseBody != null) {
                resp.set_return_code(Integer.parseInt(responseObj
                        .getString(Constants.return_code_p)));
                resp.set_message(responseObj.getString(Constants.message_p));
                error = resp.get_return_code();
                if (error == Constants.SUCCESS) {
                    i = MAX_ATTEMPTS;
                }
            }
        } catch (Exception e) {
            Log.e(DISPLAY_MESSAGE_ACTION, "Failed to send a data on attempt " + i
                    + ":" + e);
            if (i == MAX_ATTEMPTS) {
                break;
            }
            try {
                Log.d(DISPLAY_MESSAGE_ACTION, "Sleeping for " + backoff
                        + " ms before retry");
                Thread.sleep(backoff);
            } catch (InterruptedException e1) {
                // Activity finished before we complete - exit.
                Log.d(DISPLAY_MESSAGE_ACTION,
                        "Thread interrupted: abort remaining retries!");
                Thread.currentThread().interrupt();
                return error;
            }
        }
            backoff *= 2;
        }
        return error;
    }

    public ArrayList<SurveyObj> updateSurveys () {
        long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000);
        ArrayList<SurveyObj> updateSurveysArray = new ArrayList<SurveyObj>();
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpConnectionParams
                .setConnectionTimeout(httpClient.getParams(), 10000);
        JSONObject json = new JSONObject();
        for (int i = 1; i <= MAX_ATTEMPTS; i++) {
            try {
                HttpPost post = new HttpPost(Constants.URL_UPDATE_TABLES);
                StringEntity se = new StringEntity(json.toString(), HTTP.UTF_8);
                se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
                post.setHeader("Content-type", "application/json;charset=UTF-8");
                post.setEntity(se);

                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                String responseBody = httpClient.execute(post, responseHandler);
                JSONObject jsonObject = new JSONObject(responseBody);
                String temp = jsonObject.getString("data");
                JSONArray arrayJSONSurveys = new JSONArray(temp);
                //JSONArray arrayJSONSurveys = new JSONArray(responseBody);

            /* Checking response */
                if (responseBody != null) {
                  updateSurveysArray=ParserUtility.parserListCategory(arrayJSONSurveys);
                    if (updateSurveysArray.size()>0) {
                        i = MAX_ATTEMPTS;
                    }
                }
            } catch (Exception e) {
                Log.e(DISPLAY_MESSAGE_ACTION, "Failed to send a data on attempt " + i
                        + ":" + e);
                if (i == MAX_ATTEMPTS) {
                    break;
                }
                try {
                    Log.d(DISPLAY_MESSAGE_ACTION, "Sleeping for " + backoff
                            + " ms before retry");
                    Thread.sleep(backoff);
                } catch (InterruptedException e1) {
                    // Activity finished before we complete - exit.
                    Log.d(DISPLAY_MESSAGE_ACTION,
                            "Thread interrupted: abort remaining retries!");
                    Thread.currentThread().interrupt();
                    return updateSurveysArray;
                }
            }
            backoff *= 2;
        }
        return updateSurveysArray;
    }

    public void sendReport (ServerResponse response) {

    }
}
